<template>
    <div class="flex-center text-xs text-gray">
        <span class="mr-2 cursor-pointer" @click="switchPronounce">
            {{ config.defaultPronounce == "uk" ? "英" : "美" }}
        </span>

        <span
            class="cursor-pointer transition"
            @click="play"
            :class="isPlaying ? 'text-green' : ''"
        >
            [{{
                config.defaultPronounce == "uk"
                    ? w.pronounce.uk.phoneticSymbol
                    : w.pronounce.us.phoneticSymbol
            }}]
        </span>

        <audio
            class="hidden"
            ref="ukAudio"
            :src="w.pronounce.uk.audioFilePath"
        ></audio>
        <audio
            class="hidden"
            ref="usAudio"
            :src="w.pronounce.us.audioFilePath"
        ></audio>
    </div>
</template>

<script setup lang="ts">
    import { Ref, computed, onMounted, ref, watch } from "vue"
    import { useConfigStore } from "../../store/config"
    import { useWordStore } from "../../store"

    const { config } = useConfigStore()
    const { getWord } = useWordStore()

    const props = withDefaults(
        defineProps<{
            word: string
            autoplay?: boolean
            canplay?: boolean
        }>(),
        {
            canplay: true,
        }
    )

    const w = computed(() => getWord(props.word))
    const ukAudio: Ref<HTMLAudioElement> = ref() as any
    const usAudio: Ref<HTMLAudioElement> = ref() as any
    const isPlaying = ref(false)

    function switchPronounce() {
        config.defaultPronounce = config.defaultPronounce == "uk" ? "us" : "uk"
    }

    function play() {
        if (!props.canplay) {
            return
        }
        let audio =
            config.defaultPronounce == "uk" ? ukAudio.value : usAudio.value
        try {
            audio.play().catch(() => {})
        } catch {}
    }

    onMounted(() => {
        ukAudio.value.addEventListener("play", () => (isPlaying.value = true))
        ukAudio.value.addEventListener("ended", () => (isPlaying.value = false))
        usAudio.value.addEventListener("play", () => (isPlaying.value = true))
        usAudio.value.addEventListener("ended", () => (isPlaying.value = false))
        if (props.autoplay) {
            play()
        }
    })

    watch(
        () => props.autoplay,
        (c, o) => {
            if (c && !o) {
                play()
            }
        }
    )
</script>
